package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"strings"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
)

var Promote = &promoteService{}

type promoteService struct{}

func (s *promoteService) DeletePromoteList(ids string) bool {
	promoteIdList := strings.Split(ids, ",")
	if err := dao.PromoteData.DB.Transaction(func(tx *gdb.TX) error {
		if _, err := dao.PromoteData.Delete(dao.PromoteData.Columns.Id, promoteIdList); err != nil {
			return err
		}

		return nil
	}); err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}

	return true
}

func (s *promoteService) GetPromoteDataList(req *model.PromoteListReq) ([]*model.PromoteData, int) {
	var (
		data   = make([]*model.PromoteData, 0)
		total  int
		column = dao.PromoteData.Columns
	)
	if req.Id > 0 {
		promote := dao.PromoteData.GetPromoteDataOne(int(req.Id))
		total = 1

		data = append(data, promote)
	} else {
		m := dao.PromoteData.Where(g.Map{
			column.Name + " like ?":    "%" + req.Name + "%",
			column.Promote + " like ?": "%" + req.Promote + "%",
		})
		m1 := m.Clone()
		err := m.Page(req.Cur, req.PNum).Order(column.Id + " asc").Scan(&data)
		defErr.SelectRetPanic(err, data, define.DataOptFail)
		total, err = m1.Count()
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}

		if data == nil {
			return []*model.PromoteData{}, 0
		}
		var (
			createByIds []int
			updateByIds []int
		)
		for _, v := range data {
			createByIds = append(createByIds, v.CreatedBy)
			updateByIds = append(updateByIds, v.UpdatedBy)
		}

		var (
			createIdsMap = dao.MyadminUser.GetUserIdsMap(createByIds)
			updateIdsMap = dao.MyadminUser.GetUserIdsMap(updateByIds)
		)

		for _, v := range data {
			if e, ok := createIdsMap[int(v.CreatedBy)]; ok {
				v.CreatedName = e.Name
			}
			if e, ok := updateIdsMap[int(v.UpdatedBy)]; ok {
				v.UpdatedName = e.Name
			}
		}

	}
	return data, total
}
